import {
  getUserGoal,
  setUserGoal,
  updateUserGoal,
  deleteUserGoal,
  getWeightRecords,
  addWeightRecord,
  getNutritionAchievement
} from '@/api/goals'

export default {
  namespaced: true,

  state: {
    currentGoal: null,
    weightRecords: [],
    nutritionAchievement: null
  },

  mutations: {
    SET_CURRENT_GOAL(state, goal) {
      state.currentGoal = goal
    },
    SET_WEIGHT_RECORDS(state, records) {
      state.weightRecords = records
    },
    SET_NUTRITION_ACHIEVEMENT(state, data) {
      state.nutritionAchievement = data
    }
  },

  actions: {
    // 获取当前目标
    async getGoal({ commit }) {
      try {
        const res = await getUserGoal()
        commit('SET_CURRENT_GOAL', res.data)
        return res
      } catch (error) {
        console.error('获取目标失败:', error)
        throw error
      }
    },

    // 设置新目标
    async setGoal({ commit }, data) {
      try {
        const res = await setUserGoal(data)
        commit('SET_CURRENT_GOAL', res.data)
        return res
      } catch (error) {
        console.error('设置目标失败:', error)
        throw error
      }
    },

    // 更新目标
    async updateGoal({ commit }, { goalId, data }) {
      try {
        const res = await updateUserGoal(goalId, data)
        commit('SET_CURRENT_GOAL', res.data)
        return res
      } catch (error) {
        console.error('更新目标失败:', error)
        throw error
      }
    },

    // 删除目标
    async deleteGoal({ commit }, goalId) {
      try {
        await deleteUserGoal(goalId)
        commit('SET_CURRENT_GOAL', null)
      } catch (error) {
        console.error('删除目标失败:', error)
        throw error
      }
    },

    // 获取体重记录
    async getWeightRecords({ commit }, params) {
      try {
        const res = await getWeightRecords(params)
        commit('SET_WEIGHT_RECORDS', res.data)
        return res
      } catch (error) {
        console.error('获取体重记录失败:', error)
        throw error
      }
    },

    // 添加体重记录
    async addWeightRecord({ dispatch }, data) {
      try {
        const res = await addWeightRecord(data)
        // 重新获取体重记录
        await dispatch('getWeightRecords')
        return res
      } catch (error) {
        console.error('添加体重记录失败:', error)
        throw error
      }
    },

    // 获取营养达标率
    async getNutritionAchievement({ commit }, params) {
      try {
        const res = await getNutritionAchievement(params)
        commit('SET_NUTRITION_ACHIEVEMENT', res.data)
        return res
      } catch (error) {
        console.error('获取营养达标率失败:', error)
        throw error
      }
    }
  }
} 